<?php

namespace yunj\core\enum;

use yunj\app\admin\model\Setting;
use yunj\core\traits\RedisKey as RedisKeyTrait;

class RedisKey extends Enum {

    use RedisKeyTrait;

    // 后台成员id，根据token
    const ADMIN_MEMBER_ID_BY_TOKEN = "admin.member.id.by.token:";

    // 设置值获取，根据key
    const SETTING_VALUE_BY_KEY = 'setting.value.by.key:';

    /**
     * 获取完整的key。示例：RedisKey::ADMIN_MEMBER_ID_BY_TOKEN()->setArgs($token)->key()
     * @return string
     */
    public function key(): string {
        return $this->_key();
    }

    public static function allEnumAttrs(): array {
        return [
            self::ADMIN_MEMBER_ID_BY_TOKEN => [
                'desc' => '后台成员id，根据token',
                // key的后缀
                'keySuffixCall' => function (string $token) {
                    return $token;
                },
                // 原始值获取
            ],
            self::SETTING_VALUE_BY_KEY => [
                'desc' => '设置值获取，根据key',
                // key的后缀
                'keySuffixCall' => function (string $group, string $key) {
                    return $group . '.' . $key;
                },
                // 原始值获取
                'valueCall' => function (string $group, string $key) {
                    try{
                        /** @var Setting $settingModel */
                        $settingModel = app(Setting::class);
                        $data = $settingModel->getFieldValue('value',[
                            ['group', '=', $group],
                            ['key', '=', $key],
                        ]);
                        return $data;
                    }catch (\Throwable $e){
                        // 规避没有连接数据库时的访问请求
                        return false;
                    }
                }
            ]
        ];
    }

}
